import {
  FlatList,
  Image,
  ImageBackground,
  SafeAreaView,
  StatusBar,
  Text,
  ToastAndroid,
  TouchableOpacity,
  View
} from "react-native";
import React, { JSX, useEffect, useState } from "react";

import { AccountEntity, CmsItemModel, CmsModel, CmsResourceModel, fetchAccountInfo, fetchCmsData } from "./Data";
import BannerView from "../../../Component/Banner";
import Header from "./Header";
import { NavigationProp } from "@react-navigation/native";
import AccountRep from "../../../src/Account/Data/account_data.ts";
import useActiveHook from "../../../src/core/hooks/useActiveHook.ts";

function locationCode2Title(locationCode: string) {
  switch (locationCode) {
    case "icon_ticker_setup":
      return "设置与帮助";
    case "icon_ticker_tool":
      return "服务与工具";
    case "icon_ticker_welfare":
      return "鱼泡福利";
    case "icon_ticker_member":
      return "省钱专区";
  }
}

const CmsLinkUrl2Router = {
  "yupao://yupao/app/FragmentParentActivity?KEY_FRAGMENT=com.yupao.usercenter.setting.SettingFragment": "Setting"
};

type Props = {
  navigation: NavigationProp<ReactNavigation.RootParamList>
}

const UserCenter = (props: Props) => {

    const [cmsData, setCmsData] = useState<CmsModel>();
    const [accountInfo, setAccountInfo] = useState<AccountEntity>();

    useEffect(() => {
      console.log("ssss");
      fetchCmsData({ pageCode: "ucenter", userId: "20057142" }).then(value => {
        setCmsData(value);
      }).catch(reason => {
        console.log(`net error=${reason}`);
      });
    }, []);

    const accountRep = new AccountRep();
    useEffect(() => {
      accountRep.getAccountInfo().then(value => {
        setAccountInfo(value);
      });
    }, []);

    useActiveHook(() => {
      accountRep.syncAccount();
    });

    function handleCmsClick(item: CmsItemModel): void {
      const router = CmsLinkUrl2Router[item.linkUrl];
      if (!router) {
        ToastAndroid.show("功能暂未开放", ToastAndroid.SHORT);
        return;
      }
      props.navigation.navigate("Setting");
    }

    function renderItem(item: CmsResourceModel): JSX.Element {

      if (item.type == 1) {
        return <View style={{
          backgroundColor: "white",
          borderRadius: 8,
          padding: 12,
          marginHorizontal: 16,
          marginTop: 8
        }}>
          <Text style={{ fontSize: 15, fontWeight: "400", color: "black" }}>
            {locationCode2Title(item.locationCode)}
          </Text>
          <FlatList
            style={{ marginVertical: 12 }}
            data={item.list}
            horizontal={false}
            numColumns={4}
            renderItem={({ item }) => {
              return <TouchableOpacity style={{ width: "25%" }} onPress={() => handleCmsClick(item)}>
                <View style={{ alignItems: "center", marginTop: 12 }}>
                  <Image style={{ width: 36, height: 36 }} source={{ uri: item.resourceUrl }} />
                  <Text style={{ fontSize: 12, color: "gray" }}>
                    {item.title || ""}
                  </Text>
                </View>
              </TouchableOpacity>;
            }
            }
          />
        </View>
          ;
      } else {
        return <BannerView bannerData={item.list} />;
      }
    }

    const titlePaddingTop = 16 + (StatusBar.currentHeight || 0);

    const userInfoHeader = () => {
      if (accountInfo) {
        return (
          <Header account={accountInfo} />
        );
      } else {
        return (
          <></>
        );
      }
    };

    return (
      <>
        <StatusBar
          backgroundColor="transparent"
          translucent={true}
          barStyle="light-content"
        />
        <SafeAreaView style={{ flex: 1, backgroundColor: "#F5F6FA" }}>
          <ImageBackground source={require("./img/common_bg_toolbar.webp")} style={{
            paddingBottom: 16,
            paddingTop: titlePaddingTop,
            paddingHorizontal: 20,
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "flex-end"
          }}>
            <Text ellipsizeMode={"tail"} numberOfLines={1}
                  style={{ fontSize: 16, fontWeight: "600", color: "black", flex: 1 }}>
              会员中心
            </Text>

            <View style={{ flexDirection: "row" }}>
              <Image style={{ width: 18, height: 18 }} source={require("./img/account_ic_download.png")}></Image>
              <Text ellipsizeMode={"tail"} numberOfLines={1}
                    style={{ fontSize: 13, color: "black", textAlign: "right", fontWeight: "bold", marginStart: 4 }}>
                更新
              </Text>
            </View>

            <View style={{ marginStart: 16, flexDirection: "row" }}>
              <Image style={{ width: 18, height: 18 }} source={require("./img/account_ic_wallet.png")}></Image>
              <Text ellipsizeMode={"tail"} numberOfLines={1}
                    style={{ fontSize: 13, color: "black", textAlign: "right", fontWeight: "bold", marginStart: 4 }}>
                卡券
              </Text>
            </View>

            <View style={{ marginStart: 16, flexDirection: "row" }}>
              <Image style={{ width: 18, height: 18 }} source={require("./img/account_ic_service.png")}></Image>
              <Text ellipsizeMode={"tail"} numberOfLines={1}
                    style={{ fontSize: 13, color: "black", textAlign: "right", fontWeight: "bold", marginStart: 4 }}>
                客服
              </Text>
            </View>

          </ImageBackground>


          <FlatList
            data={cmsData?.resourceList}
            renderItem={
              ({ item }) => renderItem(item)
            }
            ListFooterComponent={
              <View
                style={{ marginBottom: 16 }}
              />}
            ListHeaderComponent={userInfoHeader} />
        </SafeAreaView>
      </>
    );
  }
;

export default UserCenter;
